﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Log;
using System.IO;

namespace SystemHelperLibrary.Log
{
	public class MyLog
	{
		string logName = "test.log";
		FileRecordSequence sequence = null;
		bool delete = true;

		public MyLog()
		{
			// Create a FileRecordSequence.
			sequence = new FileRecordSequence(logName, FileAccess.ReadWrite);
		}

		// Append records to the record sequence.

		public void AppendRecords(params string[] messages)
		{
			SequenceNumber previous = SequenceNumber.Invalid;

			foreach (string s in messages)
			{
				previous = sequence.Append(CreateData(s), SequenceNumber.Invalid, SequenceNumber.Invalid, RecordAppendOptions.ForceFlush);
			}
		}

		/// <summary>
		/// Read the records added to the log.
		/// </summary>
		public string ReadRecords()
		{
			Encoding enc = Encoding.UTF8;
			try
			{
				foreach (LogRecord record in this.sequence.ReadLogRecords(this.sequence.BaseSequenceNumber, LogRecordEnumeratorType.Next))
				{
					byte[] data = new byte[record.Data.Length];
					record.Data.Read(data, 0, (int)record.Data.Length);
					string mystr = enc.GetString(data);
					return mystr;
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		/// <summary>
		/// Dispose the record sequence and delete the log file. 
		/// </summary>
		public void Cleanup()
		{
			// Dispose the sequence.
			sequence.Dispose();
			// Delete the log file.
			if (delete)
			{
				try
				{
					File.Delete(this.logName);
					delete = false;
				}
				catch (Exception)
				{ }
			}
		}

		// Converts the given data to an Array of ArraySegment<byte> 

		private static IList<ArraySegment<byte>> CreateData(string str)
		{
			Encoding enc = Encoding.Unicode;
			byte[] array = enc.GetBytes(str);

			ArraySegment<byte>[] segments = new ArraySegment<byte>[1];
			segments[0] = new ArraySegment<byte>(array);

			return Array.AsReadOnly<ArraySegment<byte>>(segments);
		}
	}

}
